<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :model="filters" :inline="true">
        <el-form-item>
          <el-input v-model="filters.keywords" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" v-on:click="getCourses">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addVideo">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onLineCourse">上线</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offLineCourse">下线</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="uploadResources">上传资源</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表v-loading="listLoading"-->
    <el-table @row-click="rowClick" :data="courses" v-loading="listLoading"
              highlight-current-row style="width: 100%;">
      <!--多选框-->
      <el-table-column type="selection" width="55">
      </el-table-column>
      <!--索引值,为什么不用id,id不序号-->
      <el-table-column type="index" width="60">
      </el-table-column>
      <!--其他都设置值,只有一个不设置值就自动适应了-->
      <el-table-column prop="name" label="课程名称">
      </el-table-column>
      <el-table-column prop="logo" label="封面">
        <template scope="scope">
          <img alt="图片未找到" :src="scope.row.image" width="70px" height="70px">
        </template>
      </el-table-column>
      <!--<el-table-column prop="courseType.name" label="类型">-->
      <!--</el-table-column>-->
      <el-table-column prop="courseName" label="所属课程">
      </el-table-column>
      <el-table-column prop="lessonNumber" label="第几节" >

      </el-table-column>
      <el-table-column prop="price" label="课程价格">
      </el-table-column>
      <!--<el-table-column prop="tenantName" label="所属机构">-->
      <!--</el-table-column>-->
      <el-table-column prop="courseTypeName" label="类型">
      </el-table-column>
      <el-table-column prop="courseVideoDetail.description" label="备注">
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template scope="scope">
       
            <el-button size="small" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
       
         
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" ref="addForm">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="addForm.author" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程等级" prop="gradeId">
          <el-radio-group v-model="addForm.gradeId">
            <el-radio v-for="grade in grades" :label="grade.id">{{ grade.name }}</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="收费规则" prop="gradeId">
          <el-radio-group v-model="addForm.chargeId">
            <el-radio @change="changeCharge" v-for="charge in charges" :label="charge.id">{{ charge.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课程价格" prop="amount">
          <el-input :disabled="priceDisabled" v-model="addForm.amount" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程原价">
          <el-input :disabled="priceDisabled" v-model="addForm.priceOld" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="课程类型" prop="coursetTypId">
          <el-cascader
              :props="courseTypeProps"
              v-model="addForm.courseTypeId"
              placeholder="试试搜索：指南"
              :options="courseTypes"
              expand-trigger="hover"
              :show-all-levels="false"
              filterable
              change-on-select
          ></el-cascader>
        </el-form-item>

        <el-form-item prop="logo" label="课程封面">
          <!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
          <el-upload
              class="upload-demo"
              action="https://superjellyfish-hrm-oss.oss-cn-chengdu.aliyuncs.com"
              :data="uploadData"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>


        <el-form-item label="课程简介" prop="description">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="addForm.description">
          </el-input>
        </el-form-item>

        <el-form-item label="课程详情" prop="intro">
          <div class="edit_container">
            <quill-editor
                v-model="addForm.intro"
                ref="myQuillEditor"
                class="editer"
                :options="editorOption"
                @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!--添加视频界面-->
    <el-dialog title="新增" :visible.sync="videoFormVisible" :close-on-click-modal="false">
      <el-form :model="videoForm" label-width="80px" ref="videoForm">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="videoForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="时长" prop="duration">
          <el-input v-model="videoForm.duration" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="节数" prop="lessonNumber">
          <el-input v-model="videoForm.lessonNumber" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input v-model="videoForm.price" auto-complete="off"></el-input>
        </el-form-item>


        <el-form-item label="选择课程" prop="course">
          <el-cascader
              :props="courseProps"
              v-model="videoForm.courseId"
              placeholder="试试搜索：指南"
              :options="course"
              expand-trigger="hover"
              :show-all-levels="false"
              filterable
              change-on-select
          ></el-cascader>
        </el-form-item>

        <el-form-item prop="image" label="课程封面">
          <!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
          <el-upload
              class="upload-demo"
              action="https://superjellyfish-hrm-oss.oss-cn-chengdu.aliyuncs.com"
              :data="uploadData"
              :before-upload="beforeUpload"
              :on-success="handleLogoSuccess"
              :file-list="fileLogoList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="video" label="课程视频">
          <!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
          <el-upload
              class="upload-demo"
              action="https://superjellyfish-hrm-oss.oss-cn-chengdu.aliyuncs.com"
              :data="uploadData"
              :before-upload="beforeUpload"
              :on-success="handleVideoSuccess"
              :file-list="fileVideoList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">视频不超过5G</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="课程简介" prop="description">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="videoForm.description">
          </el-input>
        </el-form-item>

        <el-form-item label="课程详情" prop="intro">
          <div class="edit_container">
            <quill-editor
                v-model="videoForm.intro"
                ref="myQuillEditor"
                class="editer"
                :options="editorOption"
                @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="videoFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import {quillEditor} from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css"

export default {
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  components: {//使用编辑器
    quillEditor
  },
  data() {
    return {
      uploadData: {  //提交到OSS的参数
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        dir: '',
        host: ''
      },
      fileList: [], // 图片文件列表
      fileVideoList: [], // 图片文件列表
      fileLogoList: [], // 图片文件列表
      row: "",
      courseTypeProps: {
        value: "id",
        label: "name"
      },
      courseProps: {
        value: "id",
        label: "name"
      },
      priceDisabled: true,
      editorOption: {},//富文本编辑框配置
      grades: [],
      charges: [
        {"id": 1, "name": "免费"},
        {"id": 2, "name": "收费"}
      ],
      course: [],
      addFormVisible: false,
      videoFormVisible: false,
      videoForm:{

      },
      //images:[xxx.jgp,xxxx,jpg,xxxx.jpg],
      addForm: {
        id:'',
        startTime: '',
        endTime: '',
        expires: '',
        name: '',
        author: '',
        gradeId: '',
        courseTypeId: '',
        description: '',
        intro: '',
        chargeId: '',
        price: '',
        priceOld: '',
        qq: '',
        logo: '',
        pic: '',
        detailId:''
      },
      listLoading: false,
      //查询对象
      filters: {
        keywords: ''
      },
      page: 1,//当前页,要传递到后台的
      total: 0, //分页总数
      courses: [], //当前页数据
    }
  },
  methods: {
    // 给当前课程添加视频
    addVideo(row) {
      this.videoFormVisible = true;
    },
    addVideoSubmit() {
      console.log(this.videoForm)
    },
    // 删除一条课程
    del(row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        console.log(row.id);
        this.$http.delete(`/course/courseVideo/`+ row.id).then(res =>  {
          if (res.data.success) {
            this.$message.success("删除成功")
            this.getCourses();
          } else {
            this.$message.error(res.data.message)
          }
        });
      });

    },
    uploadResources(){

    },
    // 编辑
    edit(row) {
      // 清空表单
      this.videoForm = {}
      this.getAllCourse();
      // 打开模态框
      this.videoFormVisible = true;
      console.log(row)
      // console.log(this.fileList)
      this.videoForm = row
      this.videoForm.detailId = row.courseVideoDetail.id
      this.videoForm.description = row.courseVideoDetail.description
      this.videoForm.intro = row.courseVideoDetail.intro
      console.log(this.videoForm)
    },
    getUUID() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {

        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    },
    // 阿里 oss 图片上传
    async beforeUpload() {
      var _this = this;

      await this.$http.get(`/aliyunoss/aliyunoss/sign`)
          .then(response => {
            //设置相关的参数

            // debugger
            var resultObj = response.data.data;
            this.uploadData.policy = resultObj.policy;
            this.uploadData.signature = resultObj.signature;
            this.uploadData.ossaccessKeyId = resultObj.accessid;
            //上传的文件名，使用UUID处理一下 images
            this.uploadData.key = resultObj.dir + '/' + _this.getUUID() + '_${filename}';
            this.uploadData.dir = resultObj.dir;
            this.uploadData.host = resultObj.host;
            console.log(this.uploadData)
          });
    },
    handleSuccess(response, file, fileList) {
      //上传的完整的文件地址
      this.addForm.logo = this.uploadData.host + '/' + this.uploadData.key.replace("${filename}", file.name);
      // this.$message({message: '上传成功，图片地址：'+this.employee.logo, type: 'success' });
    },
    handleLogoSuccess(response, file, fileList) {
      //上传的完整的文件地址
      this.videoForm.image = this.uploadData.host + '/' + this.uploadData.key.replace("${filename}", file.name);
      // this.$message({message: '上传成功，图片地址：'+this.employee.logo, type: 'success' });
    },
    handleVideoSuccess(response, file, fileList) {
      //上传的完整的文件地址
      this.videoForm.url = this.uploadData.host + '/' + this.uploadData.key.replace("${filename}", file.name);
      // this.$message({message: '上传成功，图片地址：'+this.employee.logo, type: 'success' });
    },
    addSubmit() {
      // 没有id 添加操作
      if (this.videoForm.id == null) {

        var params = {
          // courseTypeId: this.videoForm.courseTypeId,
          duration: this.videoForm.duration,
          image: this.videoForm.image,
          lessonNumber: this.videoForm.lessonNumber,
          name: this.videoForm.name,
          courseId: this.videoForm.courseId[0],
          price: this.videoForm.price,
          url: this.videoForm.url,
          courseVideoDetail: {
            id: this.videoForm.id,
            description: this.videoForm.description,
            intro: this.videoForm.intro
          },
        }

        // courseMarket: {
        //   charge: this.videoForm.chargeId,
        //   qq: this.videoForm.qq,
        //   price: this.videoForm.price,
        //   priceOld: this.videoForm.priceOld,
        //   expires: this.videoForm.expires
        // }


        console.log(params)
        this.$http.post("/course/courseVideo", params).then(res => {
          var ajaxResult = res.data;
          if (ajaxResult.success) {
            this.$message({
              message: '添加成功!',
              type: 'success'
            });
            this.videoFormVisible = false;
            this.getCourses();
            this.videoForm = {}
          } else {
            this.$message({
              message: '上传失败!',
              type: 'error'
            });
          }
        });

      } else { // 否则修改操作
        var gradeName1;
        for (var i = 0; i < this.grades.length; i++) {
          var grades = this.grades[i];
          if (grades.id === this.videoForm.gradeId) {
            gradeName1 = grades.name;
            break;
          }
        }
        var param = {
          // courseTypeId: this.videoForm.courseTypeId,
          id: this.videoForm.id,
          duration: this.videoForm.duration,
          image: this.videoForm.image,
          lessonNumber: this.videoForm.lessonNumber,
          courseId: this.videoForm.courseId,
          name: this.videoForm.name,
          course: this.videoForm.course,
          price: this.videoForm.price,
          url: this.videoForm.url,
          courseVideoDetail: {
            id: this.videoForm.id,
            description: this.videoForm.description,
            intro: this.videoForm.intro
          },
        }
        console.log(params)

        this.$http.post("/course/courseVideo", param).then(res => {
          var ajaxResult = res.data;
          if (ajaxResult.success) {
            this.$message({
              message: '保存成功!',
              type: 'success'
            });
            this.videoFormVisible = false;
            this.getCourses();
          } else {
            this.$message({
              message: '上传失败!',
              type: 'error'
            });
          }
        });
      }
    },
    getGrades() {
      // this.$http.get("/system/systemdictionaryitem/listBySn/dj").then(result=>{
      //     this.grades = result.data.resultObj;
      // });
      this.$http.get("/system/dictionary/grade").then(result => {

        this.grades = result.data.data;
        console.log(this.grades)
        console.log(result.data)
      });
    },
    getCourseTypes() {
      this.$http.get("/course/courseType/treeData").then(result => {
        this.courseTypes = result.data.data;
      });
    },
    changeCharge(chargeId) {
      console.log(chargeId);
      if (chargeId === 1) {
        this.priceDisabled = true;
        this.addForm.amount = "";
        this.addForm.priceOld = "";
      } else {
        this.priceDisabled = false;
      }
    },
    onEditorReady(editor) {
      //当富文本编辑框初始化好执行
    },
    addHandler() {
      this.addForm = {}
      this.addFormVisible = true;
    },
    handleCurrentChange(curentPage) {
      this.page = curentPage;
      this.getCourses();
    },
    getAllCourse(){
      this.$http.get("/course/fitnessCourse/all") //$.Post(.....)
          .then(result => {
            this.videoForm.course = result.data.data
            this.course = result.data.data
          });
    },
    getCourses() {
      //发送Ajax请求后台获取数据  axios
      //添加分页条件及高级查询条件

      let courseQuery = {
          "currentPage": this.page,
          // "currentPage": 2,
          "keyword": this.filters.keywords
      };
      this.listLoading = true; //显示加载圈
      //分页查询
      this.$http.post("/course/courseVideo/pageList", courseQuery) //$.Post(.....)
          .then(result => {
            this.total = result.data.data.total;
            this.courses = result.data.data.rows;
            this.listLoading = false;  //关闭加载圈
          });
    },
    onLineCourse() {
      //获取选中的行
      if (!this.row || this.row === "") {
        this.$message({message: '老铁，你不选中数据，臣妾上不了啊....', type: 'error'});
        return;
      }

      this.$http.post("/course/course/onLineCourse/" + this.row.id).then(res => {
        var ajaxResult = res.data;
        if (ajaxResult.success) {
          this.$message({message: '老铁，上线成功.', type: 'success'});
          this.getCourses();
        } else {
          this.$message({message: ajaxResult.message, type: 'error'});
        }
      })
    },
    offLineCourse() {
      //获取选中的行
      if (!this.row || this.row === "") {
        this.$message({message: '老铁，你不选中数据，臣妾下不了啊....', type: 'error'});
        return;
      }

      this.$http.post("/course/course/offLineCourse/" + this.row.id).then(res => {
        var ajaxResult = res.data;
        if (ajaxResult.success) {
          this.$message({message: '老铁，下线成功.', type: 'success'});
          this.getCourses();
        } else {
          this.$message({message: ajaxResult.message, type: 'error'});
        }
      })
    },
    rowClick(row) {
      this.row = row;
      // console.log(this.row);
    },
    //性别显示转换
    statusFormatter: function (row, column) {
      return row.status == 1 ? '已上线' : '未上线';
    },
  },
  mounted() {
    this.getCourses();
    this.getGrades();
    this.getCourseTypes();
    this.getAllCourse();
  }
}

</script>

<style scoped>

</style>